//
//  SWSelectDevice.m
//  SerialPort
//
//  Created by MT-SW-003 on 2021/4/9.
//  Copyright © 2021 MT-SW-003. All rights reserved.
//

#import "SWSelectDevice.h"

@implementation SWSelectDevice


/*
* Check and open serial device of the device path.
*
* @param devpath The path of serial device.
*
* @return fd.
*/
+ (int)checkAndOpenDeviceByDevicePath:(NSString *)devPath {
    int fd = -1;
    NSString *regex = @"^/dev/cu.+([a-zA-Z]+-?)+[a-zA-Z0-9+-?]+";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    const char *dev = [devPath UTF8String];
    BOOL isValid = [predicate evaluateWithObject:devPath];
    NSLog(@"device Path isValid:%@",isValid?@"YES":@"NO");
    if (isValid == 1){
        fd = open(dev, O_RDWR | O_NDELAY | O_NOCTTY|O_NONBLOCK);
        if (fd == -1)
        {
        NSLog(@"open device failed fd:%d\n", fd);
        return fd;
        }
     fcntl(fd, F_SETFL, 0);//Set the file status flag value to 0 ,blocking mode
     NSLog(@"open device:%d success\n",fd);
    }
return fd;
}


/*
* scan available  serial device path，add the path to a array.
*
* @return devList The array of serial path.
*/
+ (NSArray *)scanDevice
{
    NSString *path = @"/dev/";
    NSFileManager *serialFileManager = [NSFileManager defaultManager];
    NSDirectoryEnumerator *devDirectoryEnumerator;
    devDirectoryEnumerator = [serialFileManager enumeratorAtPath:path];
    
    NSMutableArray *devList = [NSMutableArray array];

    while ((path = [devDirectoryEnumerator nextObject]) !=nil ) {
        NSString *regex = @"^cu.+([a-zA-Z]+-?)+[a-zA-Z0-9+-?]";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        
        BOOL isValid = [predicate evaluateWithObject:path];
        if(isValid == YES){
            NSMutableString *devPath = [NSMutableString stringWithFormat:@"/dev/%@",path];
            [devList addObject:devPath];
        }
    }
    return devList;
}


@end
